package com.mpgame.ctrls;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mpgame.common.proto.CmdId;
import com.mpgame.common.proto.GameGetMonsterHotbarRsp;
import com.mpgame.common.proto.GameMonsterStoreInfo;
import com.mpgame.common.proto.GamePacket;
import com.mpgame.common.utils.Log;
import com.mpgame.database.mysql.model.game.custom.MonsterDisplayInfo;
import com.mpgame.database.mysql.mapper.game.MonsterHotbarMapper;
import com.mpgame.database.mysql.translator.GameMonsterStoreInfoTranslator;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.session.SqlSessionFactory;

@RestController
@RequestMapping("/api/game")
@CrossOrigin(origins = "*")
public class GameCtrl {
    
    @Autowired
    @Qualifier("gameSqlSessionFactory")
    private SqlSessionFactory gameSqlSessionFactory;

    @GetMapping(value = "/monster-hotbar", produces = "application/x-protobuf")
    public byte[] getMonsterHotbar(
        @RequestParam(name="index", defaultValue = "-1") int index, 
        HttpServletRequest httpRequest, 
        Authentication authentication) {
        try {
            // 从Spring Security获取认证信息
            int accountId = (Integer) authentication.getPrincipal();
            
            Log.info("用户 (ID: " + accountId + ") 请求获取热槽位怪物，索引：" + index);

            List<MonsterDisplayInfo> displayInfos;
            
            if (index == -1) {
                // 获取所有槽位怪物
                try (var sqlSession = gameSqlSessionFactory.openSession()) {
                    MonsterHotbarMapper mapper = sqlSession.getMapper(MonsterHotbarMapper.class);
                    displayInfos = mapper.selectMonsterDisplayInfosByPlayerId(accountId);
                }
                Log.info("用户 " + accountId + " 热槽位中共有" + displayInfos.size() + "个怪物");
            } else if (index >= 0 && index < 6) {
                // 获取指定槽位怪物
                try (var sqlSession = gameSqlSessionFactory.openSession()) {
                    MonsterHotbarMapper mapper = sqlSession.getMapper(MonsterHotbarMapper.class);
                    MonsterDisplayInfo displayInfo = mapper.selectMonsterDisplayInfoByPlayerIdAndSlot(accountId, index);
                    displayInfos = displayInfo != null ? List.of(displayInfo) : List.of();
                }
                if (displayInfos.isEmpty()) {
                    Log.info("用户 " + accountId + " 的槽位" + index + "为空！");
                }
            } else {
                Log.err("无效的槽位索引：" + index);
                // 返回错误响应
                return GamePacket.newBuilder()
                        .setCmd(CmdId.GAME_GET_MONSTER_HOTBAR_RSP)
                        .setEc(com.mpgame.common.proto.ErrorCode.INVALID_PARAM)
                        .setData(GameGetMonsterHotbarRsp.newBuilder()
                                .setErrMsg("无效的槽位索引")
                                .build()
                                .toByteString())
                        .build()
                        .toByteArray();
            }
            
            // 转换为响应格式
            List<GameMonsterStoreInfo> monsterInfos = displayInfos.stream()
                .map(GameMonsterStoreInfoTranslator::buildMonsterStoreInfoFromDisplayInfo)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
            
            // 构建protobuf响应
            GameGetMonsterHotbarRsp.Builder rspBuilder = GameGetMonsterHotbarRsp.newBuilder().setIndex(index);
            
            // 添加怪物信息到响应
            for (GameMonsterStoreInfo monsterInfo : monsterInfos) {
                rspBuilder.addMonsterInfos(monsterInfo);
            }
            
            return GamePacket.newBuilder()
                    .setCmd(CmdId.GAME_GET_MONSTER_HOTBAR_RSP)
                    .setData(rspBuilder.build().toByteString())
                    .build()
                    .toByteArray();
            
        } catch (Exception e) {
            String errTxt = "获取怪物热槽位异常：" + e.getMessage();
            Log.err(errTxt);
            
            // 返回错误响应
            return GamePacket.newBuilder()
                    .setCmd(CmdId.GAME_GET_MONSTER_HOTBAR_RSP)
                    .setEc(com.mpgame.common.proto.ErrorCode.INTERNAL_ERROR)
                    .setData(GameGetMonsterHotbarRsp.newBuilder()
                            .setErrMsg(errTxt)
                            .build()
                            .toByteString())
                    .build()
                    .toByteArray();
        }
    }
}
